package com.ye.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.CreateBucketRequest;
import com.aliyun.oss.model.ObjectMetadata;

import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import java.util.concurrent.*;

public class OssUtil {

    private final static  String endpoint = "oss-cn-beijing.aliyuncs.com";
    private final static  String accessKeyId = "LTAI5tN2PjuJDpWMmvqBWg75";
    private final static  String accessKeySecret = "DH6j0IfOolnkytDJLOgB1JvZ4XRd77";
    private static  String bucketName = "bingoyyl123";
//    10年的链接过期时间
    private static final Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);


    public static OSS getOSSConnection() {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        if (ossClient.doesBucketExist(bucketName)) {
            System.out.println("bucket存在");
        } else {
            System.out.println("bucket不存在");
            CreateBucketRequest bucketRequest = new CreateBucketRequest(null);
            bucketRequest.setBucketName(bucketName);
            bucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
            ossClient.createBucket(bucketRequest);
        }

        return ossClient;
    }


    //    创建线程池
    static ExecutorService pool = Executors.newFixedThreadPool(2);


    /**
     * 上传部分代码
     * 对外调用的方法出口
     * @param fileName 上传文件名
     * @param input    文件输入流（加载到内存）
     * @param isMusic  判断是否为音频文件
     * @return
     */
    public static String startUpload(String fileName, InputStream input, int isMusic) {

        try {
//            submit执行上传任务
            Future<String> re = pool.submit(new doUpload(fileName, input, isMusic));
            return re.get();
        } catch (InterruptedException | ExecutionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "";
    }

    //        静态内部类
    static class doUpload implements Callable<String> {

        String fileName = "";
        InputStream input;
        int isMusic = 0;// 1音频2图片


        /**
         * 内部类构造方法
         * @param fileName
         * @param input
         * @param isMuisc
         */
        public doUpload(String fileName, InputStream input, int isMuisc) {

//            文件名重命名，规则为【原文件名+当前系统时间.后缀】
            String[] split = fileName.split("\\.");
            String newFileName = split[0]+System.currentTimeMillis()+"."+split[1];
            this.fileName = newFileName;
            this.input = input;
            this.isMusic = isMuisc;
        }

        public String call() throws Exception {

            // 创建OSSClient实例。
            OSS ossClient = OssUtil.getOSSConnection();
//            阿里云oss的一个上传sdk模块
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentLength(input.available());
            metadata.setContentEncoding("utf-8");
            metadata.setExpirationTime(expiration);
//            将文件名全部转化为小写，取后缀进行判断文件类型
            if (fileName.toLowerCase().endsWith("mp3")) {
                metadata.setContentType("audio/mp3");
            } else if (fileName.toLowerCase().endsWith("mp4")) {
                metadata.setContentType("video/mpeg4");
            } else if (fileName.toLowerCase().endsWith("wav")) {
                metadata.setContentType("audio/wav");
            } else if (fileName.toLowerCase().endsWith("jpg")) {
                metadata.setContentType("image/jpeg");
            } else if (fileName.toLowerCase().endsWith("jpeg")) {
                metadata.setContentType("image/jpeg");
            } else if (fileName.toLowerCase().endsWith("bmp")) {
                metadata.setContentType("image/bmp");
            } else if (fileName.toLowerCase().endsWith("gif")) {
                metadata.setContentType("image/gif");
            } else {// png
                metadata.setContentType("image/png");
            }
//            如果isMusic参数为1则上传到bucketName/mp3/下，否则上传到bucketName/images/
            URL url = null;
            if (isMusic == 1) {
                ossClient.putObject(bucketName, "mp3/" + fileName, input, metadata);
                url = ossClient.generatePresignedUrl(bucketName, "mp3/" + fileName, expiration);
            } else {
                ossClient.putObject(bucketName, "images/" + fileName, input, metadata);
                url = ossClient.generatePresignedUrl(bucketName, "images/"+fileName, expiration);
            }

            String fileUrl = null;
            if (url != null) {
                fileUrl = url.toString();
            }
            // 关闭OSSClient。
            ossClient.shutdown();
//            返回地址
            return fileUrl;

        }
    }

}
